<!-- 添加弹窗 -->
<template>
  <div style="margin-top: 10px;" class="wrap">
    <div>
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" label-position="top"
             @submit.native.prevent>
      <el-form-item label="客户:" prop="customer_name">
        <el-autocomplete v-model="form.customer_name" :fetch-suggestions="querySearchAsync" class="w-full"
                         placeholder="搜索客户" value-key="name" @select="handleSelect" clearable
                         :disabled="!typeFlag"
                         @clear="clearCustomer"></el-autocomplete>
      </el-form-item>

      <el-form-item label="联系人:" prop="contact_name">
        <div style="display: flex;justify-content: space-between" class="contact_nameWrap">
          <el-select v-model="form.contact_name" class="ele-block" clearable placeholder="请选择联系人"
                     :disabled="!typeFlag"
                     @change="changeContact">
            <el-option
              v-for="(item, index) in contact_nameList"
              :key="index"
              :label="item.name"
              :value="item.name+'-'+item.phone+'-'+item.id"
            />
          </el-select>
          <el-button style="margin-left: 10px" type="primary" @click="addCustomerUser" :disabled="!form.customer_id">
            新建
          </el-button>
        </div>
      </el-form-item>

      <el-form-item label="联系电话:" prop="contact_phone">
        <el-input
          disabled
          v-model="form.contact_phone"
          clearable
          placeholder=""/>
      </el-form-item>
      <el-form-item label="详细地址:" prop="address">
        <el-input
          disabled
          v-model="form.address"
          clearable
          placeholder=""/>
      </el-form-item>
      <el-form-item label="计划时间：" prop="plan_at">
        <el-date-picker
          v-model="form.plan_at"
          type="datetime"
          :picker-options="pickerOptions"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="任务描述:" prop="description">
        <el-input
          type="textarea"
          :rows="5"
          v-model="form.description"
          clearable
          placeholder="请输入任务描述"/>
      </el-form-item>
      <el-form-item label="巡检负责人：" prop="user_id">
        <PrincipalSelect :limit="false" v-model="form.user_id" placeholder="请选择巡检负责人"></PrincipalSelect>
      </el-form-item>
      <el-form-item >
        <el-button
          @click="cancel">取消
        </el-button>
        <el-button
          :loading="btnLoading"
          type="primary"
          @click="onSubmit">创建
        </el-button>
      </el-form-item>
    </el-form>
  </div>
  <addContact
    ref="AddConcat"
    :visible.sync="showCustomerUserEdit"
    @done="reset"
  />
  </div>
</template>

<script>
import {removePageTab} from '@/utils/page-tab-util'
import {mapGetters} from "vuex";
import PrincipalSelect from "@/views/project/task/components/PrincipalSelect.vue";
import addContact from "@/views/workTickets/workTickets/addWorkTicket/compoments/addContact.vue";
export default {
  components:{
    PrincipalSelect,
    addContact
  },
  computed: {
    ...mapGetters(["permission"])
  },
  data() {
    const checkCycle = (rule, value, callback) => {
      if (this.form.region && this.form.num) {
        callback()
      } else {
        callback(new Error('请选择周期'));
      }
    }
    const checkCustomer = (rule, value, callback) => {
      console.log(this.form)
      if (this.form.customer_id) {
        callback()
      } else {
        callback(new Error('请选择客户'));
      }
    };
    return {
      pickerOptions: {
        disabledDate: (time) => {
          return time.getTime() < new Date().getTime()-24*60*60*1000;
        },
        selectableRange: this.getTimeRange()
      },
      btnLoading:false,
      customer_id:'',
      form: {},
      // 是否为编辑
      typeFlag: true,
      contact_nameList:[],

      //新增联系人
      showCustomerUserEdit: false,
      rules: {
        name: [
          {required: true, message: '请输入计划巡检名称', trigger: 'blur'},
        ],
        cycle: [
          {required: true, validator: checkCycle, trigger: 'change'},
        ],
        plan_at: [
          { required: true, message: '请选择巡检任务计划时间', trigger: 'change'}
        ],
        user_id: [
          {type: 'date', required: true, message: '请选择巡检负责人', trigger: 'change'}
        ],
        customer_name: [
          {required: true, validator: checkCustomer, trigger: 'change'}
        ],
      }
    };
  },
  watch: {},
  mounted() {
  },
  methods: {
    getTimeRange(){
      let myDate = new Date(Date.now()+30*60*1000); //实例一个时间对象；
      return myDate.getHours()+':'+myDate.getMinutes()+':'+myDate.getSeconds()+':'+'-'+'23:59:59'
    },
    //清除客户
    clearCustomer() {
      this.contact_nameList = []
      this.form.contact_name = ''
      this.form.contact_phone = ''
      this.form.customer_user_id=''
      this.form.address = ''
      this.$forceUpdate()
    },
    changeContact(item) {
      this.form.contact_name = item.split('-')[0]
      this.form.contact_phone = item.split('-')[1]
      this.form.customer_user_id=item.split('-')[2]
      this.$forceUpdate()
    },
    //新增联系人
    addCustomerUser() {
      this.$refs.AddConcat.form.customer_id=this.form.customer_id
      this.$refs.AddConcat.form.customer_name=this.form.customer_name
      this.showCustomerUserEdit = true

    },
    //添加联系人之后
    reset(res) {
      this.contact_nameList.push({name: res.name, phone: res.phone,id:res.id})
      this.form.contact_phone = res.phone
      this.form.contact_name = res.name
      this.form.customer_user_id=res.id
      this.$forceUpdate()
    },
    querySearchAsync(query, cb) {
      this.$http.get("customers", {
        params: {
          keyword: query,
          page: 1,
          limit: 10
        }
      }).then((res) => {
        cb(res.data.data);
      });
    },
    //选择客户
    handleSelect(item) {
      this.form.customer_name = item.name
      this.form.customer_id = item.id
      this.contact_nameList = []
      let defaultConcat = null
      this.$forceUpdate();
      this.form.address = item.address
      if (item.users.length != 0) {
        this.contact_nameList = item.users.map((item) => {
          return {name: item.name, phone: item.phone}
        })
        //选择客户之后渲染默认联系人
        defaultConcat = item.users.filter(item => item.is_default = true)[0]
        this.form.contact_phone = defaultConcat.phone
        this.form.contact_name = defaultConcat.name
        this.form.customer_user_id = defaultConcat.id
      } else {
        this.form.contact_phone = ''
        this.form.contact_name = ''
        this.form.customer_user_id=''
      }
      if (defaultConcat) {
        this.customer_user_id = item.id
        this.contact_name = item.name
      }
    },
    cancel(){
      this.$router.push({path:'/inspection/task'})
      removePageTab('inspection/task/add');
    },
    onSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.btnLoading=true
          this.$http.post(`/pollings`,this.form).then((res) => {
            if(res.data.code === 0){
              this.$message.success(res.data.msg);
              this.$router.push({path:'/inspection/task'})
              removePageTab('inspection/task/add');
            }else {
              this.$message.error(res.data.msg);
            }
          })
          this.btnLoading=false
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

  }
}
</script>

<style scoped>


.el-autocomplete {
  width: 100%;
}

.el-input {
  width: 100% !important;
}

/deep/ .el-select{
  width: 100%;
}

.wrap {
  margin: 0 auto;
  width: 50%;
  padding-top: 30px;
}

.ele-admin-body {
  background: #fff;
}
</style>
